#pragma once 
#include <iostream>
#include <string>
#include <unordered_map>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>


class User
{
public:
    User(uint16_t port , const std::string& ip) :_port(port),_ip(ip){}

    std::string ip(){return _ip;}
    uint16_t port(){return _port;}
private:
    uint16_t _port;
    std::string _ip; 
};


class UserManage
{
public:
    //上线
    bool online(uint16_t port,const std::string& ip)
    {
        std::string id = ip + "-" + std::to_string(port); 
        auto it = _users.find(id); 
        User u(port,ip);
        //如果不在上线列表中，加入到上线列表
        if(it == _users.end()) 
        {
            _users.insert(std::make_pair(id,u));
            std::cout <<"[" <<  id << "  is online]" << std::endl;
        }
        else return false;

        return true;
    }
    //下线
    bool offline(uint16_t port,const std::string& ip)
    {
         std::string id = ip + "-" + std::to_string(port);
         auto it = _users.find(id);
         if(it != _users.end())
         {
            _users.erase(id); //移除在线列表
            std::cout <<"[" <<  id << "  is offline]" << std::endl;
            return true;
         }
         //没找到该用户，下线错误
         return false;
    }

    //用户是否在线
    bool isonline(uint16_t port,const std::string& ip)
    {
         std::string id = ip + "-" + std::to_string(port);
        auto it = _users.find(id);
        return it != _users.end();
    }

    //消息转发，把消息转发给用户列表的所有人
    void broadcastMessage(const std::string& message, int _sock,std::string ip,uint16_t port)
    {
        for(auto& u : _users)
        {
            //构建客户端sockaddr_in
            uint16_t u_port = u.second.port(); //要广播的客户端端口
            std::string u_ip = u.second.ip();  //要广播的客户端ip
            struct sockaddr_in client; 
            client.sin_family = AF_INET; 
            client.sin_port = htons(u_port); 
            client.sin_addr.s_addr = inet_addr(u_ip.c_str()); 
            //这里的ip和port是发送消息人的端口和port
            std::string response = ip + "-" + std::to_string(port) + " :" + message;

            //发送消息
            sendto(_sock,response.c_str(),response.size(),0,(struct sockaddr*)&client,sizeof client);
        }
    }

private:
    std::unordered_map<std::string,User> _users;  //记录在线用户
};